package com.yml.mall.carts;

import com.yml.mall.carts.pojo.CartsAddDTO;
import com.yml.mall.currentexception.UserLoginException;
import com.yml.mall.user.pojo.UserDO;
import com.yml.mall.vo.ResponseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import static com.yml.mall.consts.myConst.CURRENT_USER;

/**
 * @ClassName CartsController
 * @Author Administrator
 * @Date 2020/4/13   14:57
 */
@RestController
@Validated
@Slf4j
public class CartsController {

    private  final  CartsService cartsService;
    public CartsController(CartsServiceImpl cartsService){
        this.cartsService=cartsService;
    }

    /**
     * 获取购物车的所有商品
     * @param session
     * @return
     */
    @GetMapping("/carts")
    public ResponseVO carts(HttpSession session){

        UserDO userDO =(UserDO) session.getAttribute(CURRENT_USER);
        if(userDO==null) throw  new UserLoginException();
        return cartsService.getCartsVO(userDO);
    }

    @PostMapping("/carts")
    public ResponseVO carts(@RequestBody @Valid CartsAddDTO cartsAddDTO, HttpSession session){
        UserDO userDO=(UserDO)session.getAttribute(CURRENT_USER);
        if(userDO==null) throw  new UserLoginException();
        return  cartsService.add(cartsAddDTO,userDO);
    }

    @GetMapping("/carts/products/sum")
    public ResponseVO sum(HttpSession session){
        UserDO userDO= (UserDO) session.getAttribute(CURRENT_USER);

        if(userDO==null) {
            log.error("userDO==null");
            throw new UserLoginException();
        }

        return cartsService.getCartsSum(userDO);
    }

    @PutMapping("/carts/{productId}")
    public ResponseVO  addNum(@PathVariable(value = "productId")Integer productId,@RequestBody @Valid CartsAddDTO cartsAddDTO,HttpSession session){
        UserDO userDO =(UserDO) session.getAttribute(CURRENT_USER);
        if (userDO==null) throw new UserLoginException();
        cartsAddDTO.setProductId(productId);
        return cartsService.add(cartsAddDTO,userDO);
    }
}
